import smtplib

from app.core.config import Config
from app.core.core import Singleton
from app.core.log import Log


@Singleton
class Mail:
    """
    邮件发送
    """

    def __init__(self):
        config = Config().init()
        self._mail_sever = config.get("mail", "sever")
        self._mail_port = config.get("mail", "port")
        self._mail_passwd = config.get("mail", "passwd")
        self._mail_sender = config.get("mail", "sender")

        mail_receivers_str = config.get("mail", "receivers")
        self._mail_receivers = mail_receivers_str.split(",")

        self.debug = config.getboolean("mail", "debug")

        self._log = Log().init()

        self._mail_smtp = self._get_mail()

    def _get_mail(self):
        """获取email对象实例"""

        mail_smtp = smtplib.SMTP()
        mail_smtp.connect(self._mail_sever, self._mail_port)
        mail_smtp.login(self._mail_sender, self._mail_passwd)

        return mail_smtp

    def sendmail(self, msg, mail_options=(), rcpt_options=()):
        """原生方法调用发送邮件"""

        result = True

        if self.debug:
            self._log.debug("** mail debug **")
            self._log.debug(self._mail_sever)
            self._log.debug(self._mail_port)
            self._log.debug(self._mail_passwd)
            self._log.debug(self._mail_sender)
            self._log.debug(self._mail_receivers)

            self._log.debug(msg["Subject"])
            self._log.debug(msg["From"])
            self._log.debug(msg["To"])
        else:
            try:
                self._mail_smtp.sendmail(self._mail_sender, self._mail_receivers, msg.as_string(),
                                         mail_options,
                                         rcpt_options)
            except Exception as e:
                self._log.error("email send error:")
                self._log.error(e.args)
                result = False

        return result

    def __del__(self):
        self._mail_smtp.quit()  # 关闭连接
